package com.service.dialtest.controller;

import com.service.dialtest.dto.LoginUserDto;
import com.service.dialtest.dto.WebUserDto;
import com.service.dialtest.dto.WebUserInfoDto;
import com.service.dialtest.entity.WebUserInfo;
import com.service.dialtest.service.UserInfoService;
import com.service.config.utils.*;
import com.service.dialtest.vo.WebUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.service.dialtest.constant.Constant.*;
import static com.service.config.constant.Constant.USERNAME_OR_NOTFOUND;
import static com.service.config.constant.Constant.USER_INFO;
import static com.service.config.constant.Constant.USER_NOT_FOUND;

/**
 * 用户controller
 * @author hjl
 */
@CrossOrigin
@RestController()
@RequestMapping("/webUserLogin")
@Api(value = "web用户")
public class WebUserController {
    /**
     * 服务对象
     */
    @Resource()
    private UserInfoService userInfoService;
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 统一登录
     *
     * @param
     * @return
     */
    @PostMapping(value = "auth",produces="application/json")
    @ApiOperation(value = "统一登录")
    @ResponseBody
    public Result loginManage(HttpServletRequest httpServletRequest, @RequestBody LoginUserDto loginUserDto) throws Exception {
        HashMap map = new HashMap();
        if(loginUserDto.getUsername() == null || "".equals(loginUserDto.getUsername())
                || "".equals(loginUserDto.getPassword()) || loginUserDto.getPassword() == null){
            return Result.failure(10003,"用户名或密码为空");
        }
        map = userInfoService.getToken(loginUserDto,httpServletRequest);
        if(map == null){
            return Result.failure(USER_NOT_FOUND,"用户不存在");
        }
        return Result.ok().setData(map);
    }

    /**
     * 用户标准注册
     *
     * @param
     * @return
     */
    @PostMapping(value = "register",produces="application/json")
    @ApiOperation(value = "用户标准注册")
    @ResponseBody
    public Result register(HttpServletRequest httpServletRequest,@RequestBody WebUserInfoDto userInfoDto) throws Exception {
        if(userInfoDto.getUsername() == null || "".equals(userInfoDto.getUsername())
                || "".equals(userInfoDto.getPassword()) || userInfoDto.getPassword() == null){
            return Result.failure(USERNAME_OR_NOTFOUND,"用户名或密码为空,请重新输入");
        }
        String realIp = getRealIp(httpServletRequest);
        return userInfoService.register(userInfoDto,realIp);
    }

    /**
     * 退出登录
     *
     * @param
     * @return
     */
    @RequestMapping(value =  "logout",method = RequestMethod.GET,produces="application/json")
    @ApiOperation(value = "退出登录")
    @ResponseBody
    public Result logout(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 缓存是否存在
                String value = redisUtil.getValue(cloudAuthToken + userId);
                WebUserInfo userDto = JsonXMLUtils.json2obj(value, WebUserInfo.class);
                userDto.setOffTime(new Date());
                userDto.setOnlineTime(DateUtil.getDateMin(DateUtil.datetoString(userDto.getDate()), DateUtil.datetoString(new Date())));
                WebUserInfo userInfo = new WebUserInfo();
                userInfo.setId(userId);
                userInfo.setIp(userDto.getIp());
                userInfo.setOnlineTime(userDto.getOnlineTime());
                userInfo.setOffTime(userDto.getOffTime());
                userInfo.setStatus("1");
                userInfoService.update(userInfo);
                redisUtil.leftPush(USER_INFO,JsonXMLUtils.obj2json(userDto));
                redisUtil.delete(cloudAuthToken+userId);
                return Result.ok();
            }else {
                return Result.failure(USERNAME_OFF_SITE,LOGIN_INFO_HAS_EXPIRED);
            }
        }else {
            return Result.failure(USER_NOT_LOGIN,"用户未登录");
        }
    }

    /**
     * 点击账号名可查询用户个人信息
     *
     * @param
     * @return
     */
    @RequestMapping(value =  "queryUserDetail",method = RequestMethod.GET,produces="application/json")
    @ApiOperation(value = "查询用户个人信息")
    @ResponseBody
    public Result queryUserDetail(@RequestHeader(value = "cloud-Auth-Token") String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken + userId)) {
                String value = redisUtil.getValue(cloudAuthToken + userId);
                WebUserDto userDto = JsonXMLUtils.json2obj(value, WebUserDto.class);

                return userInfoService.queryByUserId(userId);
            } else {
                return Result.failure(USERNAME_OFF_SITE, LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.failure(USER_NOT_LOGIN, "用户未登录");
    }

    /**
     * 修改密码/信息
     * @param
     * @return
     */
    @RequestMapping(value =  "/retrieve",method = RequestMethod.POST,produces="application/json")
    @ApiOperation(value = "修改个人信息")
    @ResponseBody
    public Result retrieve(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                           @RequestBody WebUserInfoDto userInfoDto) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            String userId = UserTokenManager.getUserId(cloudAuthToken);
            if (redisUtil.exist(cloudAuthToken+userId)) { // 密码修改
                return userInfoService.updateUserInfo(userInfoDto);
            }else {
                return Result.failure(USERNAME_OFF_SITE,LOGIN_INFO_HAS_EXPIRED);
            }
        }
        return Result.ok();
    }

    /**
     * 清除缓存
     * @param strings
     * @param redisUtil
     */
    public static void clearCache(Set<String> strings, RedisUtil redisUtil) {
        strings.stream().forEach(
                s -> {
                    String value = redisUtil.getValue(s);
                    try {
                        WebUserDto userDto1 = JsonXMLUtils.json2obj(value, WebUserDto.class);
                        userDto1.setOffTime(new Date());
                        long dateMin = DateUtil.getDateMin(DateUtil.datetoString(userDto1.getDate()), DateUtil.datetoString(new Date()));
                        userDto1.setOnlineTime(dateMin); // 在线时长
                        redisUtil.leftPush(USER_INFO,JsonXMLUtils.obj2json(userDto1));
                        redisUtil.delete(s);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );
    }

    public String getRealIp(HttpServletRequest request) {
        return getString(request);

    }

    public static String getString(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        ip = getString(request, ip);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getString(HttpServletRequest request, String ip) {
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        return ip;
    }
}
